<template>
  <div class="p-2" v-if="dataInfo.uuid">
    <van-row v-if="showSearch" justify="center" align="center">
      <van-col span="2">
        <van-image :src="dataInfo.search.thumb" :width="40" :height="40">
          <template v-slot:error>加载失败</template>
        </van-image>
      </van-col>
      <van-col span="22">
        <van-search
            v-model="searchValue"
            placeholder="输入关键词搜索"
            action-text="取消"
            @search="onSearch"
            @cancel="onCancel"
        />
      </van-col>
    </van-row>

    <div class="banner">
      <van-swipe :autoplay="dataInfo.carousel.interval" indicator-color="#1989fa" class="w-full" style="height: 50vw">
        <van-swipe-item v-for="(item, index) in dataInfo.carousel.banner" :key="index">
          <van-image @click="goToUrl(item.url)" :src="item.thumb" width="100%" height="100%" fit="cover" />
        </van-swipe-item>
      </van-swipe>
    </div>

    <div class="nav pt-2">
      <van-tabs
          v-model:active="active"
          color="#7F80EF"
          :swipe-threshold="5"
          title-active-color="#333333"
          title-inactive-color="#999999"
          :ellipsis="false"
      >
        <van-tab v-if="dataInfo.navigation.length > 0"
                 :title-style="getTitleStyle('all')"
                 name="all"
                 title="全部"/>
        <van-tab v-for="(item) in dataInfo.navigation"
                 :key="item.uuid"
                 :title-style="getTitleStyle(item.uuid)"
                 :name="item.uuid"
                 :title="item.name"/>
      </van-tabs>

      <div class="listBox p-3 pt-4">
        <van-list
            v-model="loading"
            :finished="finished"
            :immediate-check="false"
            finished-text="没有更多了"
            @load="getDataList"
        >
          <template v-for="content of dataList" :key="content.uuid">
            <van-row class="mb-2" @click="showDetail(content.entity_uuid)">
              <van-col span="16">
                <div class="flex flex-col pr-3">
                  <span class="font-bold text-lg text-custom-gray3 pb-2">{{ limitedContent(content.name,25) }}</span>
                  <span v-if="content.type == 1" class="text-custom-gray9 text-sm pb-2">
                     <div class="flex flex-row pb-2 pr-6">
                        <span class="block text-xm text-gray-500 bg-gray-100 mr-2 pl-1 pr-1" v-for="sub in content.subject">#{{sub}}</span>
                      </div>
                  </span>
                  <span v-if="content.type == 2" class="text-custom-gray9 text-sm pb-2">
                    <van-text-ellipsis rows="2" :content="limitedContent(content.content,60)" />
                  </span>
                  <span class="text-custom-gray9 text-sm">
                    <van-icon name="clock-o" /> {{ content.created_at }}
                  </span>
                </div>
              </van-col>
              <van-col span="8">
                <van-image width="132" height="100" :src="content.thumb" radius="5" />
              </van-col>
            </van-row>
            <van-divider />
          </template>
        </van-list>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue';
import { aggListContentList, aggListItemsType, aggListInfo, aggListType } from '@/api/aggList.ts';
import { Meta } from '@/api/models';
import { useRouter } from 'vue-router';

const props = defineProps<{
  customerUuid: string,
  aggListUuid:string,
  showSearch:boolean
}>();
const router = useRouter();
const aggListUuid = props.aggListUuid
const customerUuid = props.customerUuid


const dataInfo = reactive<aggListType>({
  uuid: '',
  mid: 0,
  name: '',
  status: 1,
  type: 1,
  search: {
    thumb: '',
    material_uuid: '',
  },
  carousel: {
    interval: 0,
    banner: [],
  },
  navigation: [],
});

const active = ref('all');
const dataList = reactive<aggListItemsType[]>([]);
const searchValue = ref('');

const getTitleStyle = (index: string) => ({
  fontWeight: index === active.value ? 'bold' : 'normal',
});

const onSearch = () => {
  console.log('onSearch');
};
const onCancel = () => {
  console.log('onCancel');
};

onMounted(async () => {
  await getAggListInfo()
  if(props.showSearch){

  }
});

const getAggListInfo = async () => {
  try {
    const response = await aggListInfo(aggListUuid);
    if(response.data){
      Object.assign(dataInfo,response.data)
    }
  } catch (e) {
    console.error(e);
  }
};

const showDetail = (entityUuid: string) => {
  switch (dataInfo.type){
    case 1:
      router.push(`/dist/${customerUuid}/content/${entityUuid}/${aggListUuid}`);
      break;
    case 2:
      router.push(`/dist/${customerUuid}/campaign/${entityUuid}/${aggListUuid}`);
      break;
  }
};
const goToUrl = (url:string)=>{
  if(url){
    window.location.href = url;
  }
}

interface queryParam {
  query: {
    agg_uuid?: string;
    nav_uuid?: string;
  };
  page: number;
  sort: string;
  perPage: number;
}

const queryParam = reactive<queryParam>({
  query: {},
  page: 1,
  sort: '-created_at',
  perPage: 10,
});

const meta = ref<Meta>({
  totalCount: 0,
  pageCont: 0,
  currentPage: 1,
  perPage: 10,
});
const loading = ref(false);
const finished = ref(false);
let isFetching = false; // 标识是否正在获取数据

const getDataList = async () => {
  if (finished.value || isFetching) return; // 如果已经完成或正在获取数据，直接返回
  loading.value = true;
  isFetching = true;

  try {
    const response = await aggListContentList(aggListUuid,{
      ...queryParam,
      query: JSON.stringify(queryParam.query),
    });

    meta.value = response.data._meta;
    const data = response.data.items;

    if (data.length > 0) {
      dataList.push(...data);
      queryParam.page++;
      finished.value = dataList.length >= meta.value.totalCount;
    } else {
      finished.value = true;
    }
  } catch (e) {
    console.error(e);
    finished.value = true;
  } finally {
    loading.value = false;
    isFetching = false;
  }
};

watch(
    () => active.value,
    async (newValue) => {
      queryParam.page = 1;
      if (newValue !== 'all') {
        queryParam.query.nav_uuid = newValue;
      }else{
        delete queryParam.query.nav_uuid
      }
      dataList.length = 0;
      finished.value = false;

      await getDataList(); // 只在状态重置完成后获取数据
    },
    { immediate: true }
);



const limitedContent = (str:string,len:number) => {
  return str.length > len ? str.slice(0, len) + '...' : str;
};
</script>

<style scoped></style>
